#!python
import unittest
import pbfi
import samples.simple 
import samples.array 

EPSILON = 0.00000005

def check_memory_layout(blocks, values):
    """
    Flatten the block list and compare to the test values
    special case for float due to python using double precision by default
    """
    for block in blocks:
        if block['format'] == 'array':
            check_memory_layout(block['value'], values)
        else:
            nvalue = values.next()
            bvalue = block['value']
            if type(bvalue) == float:
                if nvalue != 0.0:
                    diff = (bvalue-nvalue)/nvalue 
                    if diff > EPSILON: 
                        return False
                elif bvalue != 0.0:
                    return False
            elif bvalue != nvalue: 
                return False
    return True

class ReaderTest(unittest.TestCase):

    def test_simple(self):
        samples.simple.main()
        bfi = pbfi.BinaryFileInspector()
        bfi.load_model("samples/"+samples.simple.MODEL)
        bfi.load(samples.simple.FILE)
        blocks = bfi.blocks 
        fail = check_memory_layout(blocks, iter(samples.simple.VALUES))
        self.failUnless(fail)

    def test_array(self):
        samples.array.main()
        bfi = pbfi.BinaryFileInspector()
        bfi.load_model("samples/"+samples.array.MODEL)
        bfi.load(samples.array.FILE)
        blocks = bfi.blocks 
        fail = check_memory_layout(blocks, iter(samples.array.VALUES))
        self.failUnless(fail)

def main():
    unittest.main()

if __name__ == '__main__':
    main()

